# -*- coding: utf-8 -*-
import re
import redis

from Lactationer_Master import settings


class redisClient(object):
    pool = redis.ConnectionPool(host=settings.REDIS_HOST,
                                port=settings.REDIS_PORT,
                                password=settings.REDIS_PASSWORD,
                                db=settings.REDIS_DBNAME)
    r = redis.Redis(connection_pool=pool)

    # redis去重
    def checkExist(func):
        def wrapper(*args, **kw):
            exists = redisClient.r.sismember('Lactationer:exists', args[1])
            if exists == False:
                redisClient.r.sadd('Lactationer:exists', args[1])
                return func(*args, **kw)
            else:
                redisClient.r.sadd('Lactationer:alreadyExists', args[1])
                print('get already values %s' % args[1])
        return wrapper


    #插入城市key，slave先获取城市。再根据城市获取该城市的url
    @checkExist
    def setCitys(self, url):
        matchObj = re.match(r'(http://)(.*)(\.ganji\.com)', url, re.M | re.I)
        if matchObj:
            self.r.sadd('Lactationer:citys', matchObj.group(2))
        else:
            print('city urls is not mattch %s' % url)
            redisClient.r.sadd('Lactationer:failurl', url)

    #根据城市，添加这座城市的url
    @checkExist
    def setCityUrls(self, url):
        matchObj = re.match(r'(http://)(.*)(\.ganji\.com)', url, re.M | re.I)
        if matchObj:
            self.r.sadd('Lactationer:citys:' + matchObj.group(2), url)
        else:
            print('city urls is not mattch %s' % url)
            redisClient.r.sadd('Lactationer:failurl', url)